﻿using CommonLib.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace CommonLib.Base;

public abstract class BaseLexer
{

    public string Txt { get; set; } = string.Empty;

    public string Real
    {
        get
        {
            if (string.IsNullOrEmpty(Txt)) return string.Empty;
            else if(Txt.Contains('÷')) return Txt[..Txt.IndexOf('÷')].RealSql();
            else return Txt.RealSql();
        }
    }

    public abstract bool Check();

    protected abstract BaseCodeEntity Run();

    public BaseCodeEntity Execute()
    {
        try
        {
            return Run();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }
    }

    public BaseLexer Init(string txt)
    {
        this.Txt = txt;
        return this;
    }

    public BaseLexer Init(List<string> Lines)
    {
        this.Txt = string.Join("÷", Lines);
        return this;
    }

    public string Comment
    {
        get
        {
            var code = Txt;
            if (code.Contains("--"))
            {
                Txt = code[..code.IndexOf("--")].Trim();
                return code[code.IndexOf("--")..].Trim();
            }
            if (code.Contains("/*") && code.Contains("*/"))
            {
                var mats = Regex.Matches(code, "/\\*(.*?)\\*/");
                var sub = new List<string>();
                foreach (Match mat in mats.Cast<Match>())
                {
                    var val = mat.Result("$1");
                    sub.Add(val);
                    code = code.Replace(val, "");
                }
                Txt = code;
                return string.Join("", sub);
            }
            return string.Empty;
        }
    }


    protected void ListParams(string str, List<BaseCodeEntity> list, string comma = ",")
    {
        var arr = str.TrimSplit(comma);
        for (int i = 0; i < arr.Length; i++)
        {
            var item = arr[i];
            while (!item.IsFull())
            {
                var next = arr[++i];
                item = $"{item}{comma}{next}";
            }
            list.Add(SqlFactory.Create(item).Execute());
        }
    }
}
